package com.itxx.examination3;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ExaminationServer {
    //需求：编写客户端和服务器端程序，客户端用于上传图片，服务器端用于接收文件，文件上传成功后，给客户端一个反馈：文件上传成功。
    //
    //注意：
    //
    //服务器端采用多线程实现，并且要解决文件名冲突问题。
    //
    //客户端控制台内容
    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(45433);

        //自定义线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(20,
                20,
                5,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        while (true) {
            //2.调用accept()阻塞方法等待客户端连接,如果有客户端链接,则返回对应的socket对象.
            Socket socket = serverSocket.accept();
            //3.开启一个线程对象将返回的socket传入,开启多线程 [将线程start了实际上就和main方法没什么关系,main方法是一个线程,FileUpLoadSocketThread也是线程]
            executor.submit(new FileUpLoadSocketThread(socket));
        }
        //创建缓冲字节流接受数据


    }
}

class FileUpLoadSocketThread implements Runnable {
    private Socket socket;

    public FileUpLoadSocketThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(socket.getInputStream());
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\" + UUID.randomUUID().toString().replace("-", "") + ".jpg"));
            int len;
            byte[] bytes = new byte[1024];
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
                bos.flush();
            }
            String Feedback = "上传完毕";
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write("文件在" + LocalDateTime.now() + "上传完毕");
            bw.flush();
            //释放资源
            socket.close();

            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}